package com.hyt.it.ogt.ykcj.service.exchange.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.it.ogt.ykcj.common.core.domain.BaseEntity;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.PublishTypeEnums;
import com.hyt.it.ogt.ykcj.common.enums.ShowTypeEnums;
import com.hyt.it.ogt.ykcj.common.exception.CustomException;
import com.hyt.it.ogt.ykcj.domain.exam.ExamInfo;
import com.hyt.it.ogt.ykcj.domain.exchange.ExamineeExamInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.grade.ExamPublishInfo;
import com.hyt.it.ogt.ykcj.domain.grade.ExamineeExamPaperInfo;
import com.hyt.it.ogt.ykcj.domain.vo.ExamInfoVo;
import com.hyt.it.ogt.ykcj.domain.vo.exchange.CandidateAnswersVO;
import com.hyt.it.ogt.ykcj.domain.vo.exchange.CandidatePaperDataVO;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exchange.ExamineeExamInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.ExamPublishInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.ExamineeExamPaperInfoMapper;
import com.hyt.it.ogt.ykcj.service.exchange.IExamineeExamInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description
 *
 * @author yaojian
 * @createTime 2021/12/27
 */
@Slf4j
@Service
public class ExamineeExamInfoServiceImpl implements IExamineeExamInfoService {

    @Autowired
    private ExamineeExamInfoMapper examineeExamInfoMapper;

    @Autowired
    private ExamPublishInfoMapper examPublishInfoMapper;

    @Autowired
    private ExamInfoMapper examInfoMapper;

    @Autowired
    private ExamineeExamPaperInfoMapper examineeExamPaperInfoMapper;

    @Autowired
    private EnterpriseExamineeInfoMapper enterpriseExamineeInfoMapper;

    @Override
    public CandidateAnswersVO getExamInfo(String examId, String examineeId) {
        List<String> examIds = new ArrayList<>();
        List<String> examineeIds = new ArrayList<>();
        List<ExamInfoVo> examInfoVos = getExamInfoVos(examId);
        //考试组（关联考试）
        if(!CollectionUtils.isEmpty(examInfoVos)){
            examIds.addAll(examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList()));
            EnterpriseExamineeInfo enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoById(examineeId);
            for (ExamInfoVo examInfoVo :examInfoVos){
                EnterpriseExamineeInfo enterpriseExamineeParam = new EnterpriseExamineeInfo();
                enterpriseExamineeParam.setExamId(examInfoVo.getId());
                enterpriseExamineeParam.setName(enterpriseExamineeInfo.getName());
                enterpriseExamineeParam.setIdcard(enterpriseExamineeInfo.getIdcard());
                List<EnterpriseExamineeInfo>  enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoListRealName(enterpriseExamineeParam);
                examineeIds.addAll(enterpriseExamineeInfos.stream().map(e->e.getId()).collect(Collectors.toList()));
            }

        }else {
            //普通考试
            examIds.add(examId);
            examineeIds.add(examineeId);
        }

        //查询考生id集合
        QueryWrapper<ExamineeExamInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(ExamineeExamInfo::getExamId, examIds).in(ExamineeExamInfo::getExamineeId, examineeIds);
        List<ExamineeExamInfo> examineeExamInfos = examineeExamInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(examineeExamInfos)) {
            throw new CustomException("暂无该考生的考试试卷信息");
        }
        //获取查看显示不显示试卷正确答案和解析
        QueryWrapper<ExamPublishInfo> examPublishWrapper = new QueryWrapper<>();
        examPublishWrapper.lambda().eq(ExamPublishInfo::getExamId, examId).eq(ExamPublishInfo::getPublishType, PublishTypeEnums.PUBLISH_TYPE_1.getCode());
        List<ExamPublishInfo> examPublishInfos =  examPublishInfoMapper.selectList(examPublishWrapper);
        if(CollectionUtils.isEmpty(examPublishInfos)){
            throw new CustomException("暂无发布考试答案");
        }
        try {
            //查询出可以显示的paperId
            QueryWrapper<ExamineeExamPaperInfo> examineeExamPaperInfoWrapper = new QueryWrapper<>();
            examineeExamPaperInfoWrapper.lambda().eq(ExamineeExamPaperInfo::getExamPublishId, examPublishInfos.get(0).getId()).in(ExamineeExamPaperInfo::getExamId, examIds);
            List<ExamineeExamPaperInfo> examineeExamPaperInfos = examineeExamPaperInfoMapper.selectList(examineeExamPaperInfoWrapper);
            if(CollectionUtils.isEmpty(examineeExamPaperInfos)){
                throw new CustomException("暂无发布考试试卷及答案");
            }
            Map<String,Integer> paperMap = examineeExamPaperInfos.stream().collect(Collectors.toMap(e -> e.getPaperId(), ExamineeExamPaperInfo::getShowPaperResult, (key1, key2) -> key2));
            if(examPublishInfos.get(0).getShowType().indexOf(ShowTypeEnums.SHOW_TYPE_3.getCode()) > -1){
                List<CandidatePaperDataVO> candidatePaperDataList = new ArrayList<>(examineeExamInfos.size());
                CandidateAnswersVO candidateAnswersVO = new CandidateAnswersVO();
                for (ExamineeExamInfo examineeExamInfo :examineeExamInfos) {
                    candidateAnswersVO = JSON.parseObject(examineeExamInfo.getExamineeExamInfo(),CandidateAnswersVO.class);
                    Iterator<CandidatePaperDataVO> iterator = candidateAnswersVO.getCandidatePaperDataList().iterator();
                    while (iterator.hasNext()){
                        CandidatePaperDataVO candidatePaperDataVO = iterator.next();
                        if(MapUtils.isNotEmpty(paperMap)
                                && 1 != paperMap.get(candidatePaperDataVO.getPaperId()) ){
                            iterator.remove();
                        }
                    }
                    candidatePaperDataList.addAll(candidateAnswersVO.getCandidatePaperDataList());
                }
                candidateAnswersVO.setCandidatePaperDataList(candidatePaperDataList);

                // 判断是否显示答案和解析
                ExamPublishInfo examPublishInfo = examPublishInfos.get(0);
                Date startDay = examPublishInfo.getStartDay();
                Date endDay = examPublishInfo.getEndDay();
                candidateAnswersVO.setShowAnaAndAns(Boolean.FALSE);
                if(CommonEnums.SEE_TYPE_0.getCode().equals(String.valueOf(examPublishInfo.getSeeType()))){
                    candidateAnswersVO.setShowAnaAndAns(Boolean.TRUE);
                }else{
                    boolean in = DateUtil.isIn(DateUtil.date(), startDay, endDay);
                    if(in){
                        candidateAnswersVO.setShowAnaAndAns(Boolean.TRUE);
                    }
                }
                return candidateAnswersVO;
            }else if(examPublishInfos.get(0).getShowType().indexOf(ShowTypeEnums.SHOW_TYPE_4.getCode()) > -1){
                List<CandidatePaperDataVO> candidatePaperDataList = new ArrayList<>(examineeExamInfos.size());
                CandidateAnswersVO candidateAnswersVO = new CandidateAnswersVO();
                for (ExamineeExamInfo examineeExamInfo :examineeExamInfos) {
                    String strExam = examineeExamInfo.getExamineeExamInfo().replaceAll("\"answer\":","\"answer1\":").replaceAll("\"description\":","\"description1\":");
                    candidateAnswersVO = JSON.parseObject(strExam,CandidateAnswersVO.class);
                    Iterator<CandidatePaperDataVO> iterator = candidateAnswersVO.getCandidatePaperDataList().iterator();
                    while (iterator.hasNext()){
                        CandidatePaperDataVO candidatePaperDataVO = iterator.next();
                        if(MapUtils.isNotEmpty(paperMap)
                                && 1 != paperMap.get(candidatePaperDataVO.getPaperId())){
                            iterator.remove();
                        }
                    }
                    candidatePaperDataList.addAll(candidateAnswersVO.getCandidatePaperDataList());
                }
                candidateAnswersVO.setCandidatePaperDataList(candidatePaperDataList);
                candidateAnswersVO.setShowAnaAndAns(Boolean.FALSE);
                return candidateAnswersVO;
            }


        }catch (Exception e){
            log.error("getExamInfo解析试卷异常:{}",e);
            throw new CustomException("解析数据出错！");
        }
        return null;
    }

    private  List<ExamInfoVo>  getExamInfoVos(String examId){
        List<ExamInfoVo> examInfoVos = null;
        ExamInfo examInfo  = examInfoMapper.selectExamInfoById(examId);
        if(null != examInfo && null != examInfo.getMergeType() &&
                CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))){
            Map<String,Object> parms = new HashMap<>();
            parms.put("relationId",examId);
            examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
        }

        return examInfoVos;
    }

    @Override
    public int saveOrUpdate(ExamineeExamInfo examineeExamInfo) {
        //如果已有考试考生考试的试卷，那么就进行更新
        QueryWrapper<ExamineeExamInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExamineeExamInfo::getExamId, examineeExamInfo.getExamId())
                .eq(ExamineeExamInfo::getExamineeId, examineeExamInfo.getExamineeId());
        ExamineeExamInfo examineeExamInfo1 = examineeExamInfoMapper.selectOne(wrapper);
        if (examineeExamInfo1 == null || StringUtils.isEmpty(examineeExamInfo1.getId())) {
            return examineeExamInfoMapper.insert(examineeExamInfo);
        } else {
            return examineeExamInfoMapper.update(examineeExamInfo, wrapper);
        }
    }

    @Override
    public List<ExamPublishInfo> listByExamInfoId(String examInfoId) {
        LambdaQueryWrapper<ExamPublishInfo> queryWrapper = Wrappers.<ExamPublishInfo>lambdaQuery()
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .eq(ExamPublishInfo::getExamId, examInfoId);
        return examPublishInfoMapper.selectList(queryWrapper);
    }

}
